package main

import (
	"encoding/csv"
	"fmt"
	"io"
	"log"
	"os"
	"strconv"
)

type CSVRecord struct {
	SepalLength float64
	SepalWidth  float64
	PetalLength float64
	PetalWidth  float64
	Species     string
	ParseError  error
}

func main() {
	f, _ := os.Open("E:\\JetBrains\\GoglandProjects\\go_machine_learn\\data\\iris.csv")
	defer f.Close()
	reader := csv.NewReader(f)
	reader.FieldsPerRecord = 5
	var records []CSVRecord
	for {
		record, e := reader.Read()
		if e == io.EOF {
			break
		}
		if e != nil {
			log.Println(e)
			continue
		}
		var rd CSVRecord
		for idx, value := range record {
			if idx == 4 {
				if value == "" {
					rd.ParseError = fmt.Errorf("最后种类不能为空")
					break
				}
				rd.Species = value
				continue
			}
			var val float64
			if val, e = strconv.ParseFloat(value, 64); e != nil {
				rd.ParseError = fmt.Errorf("不能转换%s", e.Error())
				break
			}
			switch idx {
			case 0:
				rd.SepalLength = val
			case 1:
				rd.SepalWidth = val
			case 2:
				rd.PetalLength = val
			case 3:
				rd.PetalWidth = val
			}
		}
		if rd.ParseError == nil {
			records = append(records, rd)
		}
	}
	for i, v := range records {
		log.Println(i, v)
	}
	log.Println("records=>", len(records))
}
